package com.bjmashibing.system.OSFileIO.davidDemo;

import java.nio.IntBuffer;
import java.security.SecureRandom;

public class NIOBufferFlipTest {
    public static void main(String[] args) {
        demo1();
        demo2();



    }

    private static void demo1(){
        //分配内存大小为10的缓冲区
        IntBuffer buffer = IntBuffer.allocate(10);

        for (int i=0;i<5;i++){
            int randomNumber=new SecureRandom().nextInt(20);
            buffer.put(randomNumber);
        }
        buffer.flip();
        while (buffer.hasRemaining()){
            System.out.println(buffer.get());
        }
    }

    private static void demo2(){
        //分配内存大小为10的缓冲区
        IntBuffer buffer = IntBuffer.allocate(10);

        System.out.println("capacity:"+buffer.capacity());

        for (int i=0;i<5;i++){
            int randomNumber=new SecureRandom().nextInt(20);
            buffer.put(randomNumber);
        }


        System.out.println("before flip limit:"+buffer.limit());

        buffer.flip();

        System.out.println("after flip limit:"+buffer.limit());

        System.out.println("enter while loop");

        while (buffer.hasRemaining()){
            System.out.println("position:"+buffer.position());
            System.out.println("limit:"+buffer.limit());
            System.out.println("capacity:"+buffer.capacity());
            System.out.println("元素:"+buffer.get());

        }
    }

}
